package com.lh.job.task;

import com.lh.common.entity.admin.Order;
import com.lh.common.entity.admin.OrderStatusLog;
import com.lh.common.entity.state.RemarkEnum;
import com.lh.common.enums.IF;
import com.lh.common.enums.OrderStatusEnum;
import com.lh.job.config.PayPalConfig;
import com.lh.job.dao.OrderMapper;
import com.lh.job.dao.OrderStatusLogMapper;
import com.paypal.api.payments.Amount;
import com.paypal.api.payments.DetailedRefund;
import com.paypal.api.payments.RefundRequest;
import com.paypal.api.payments.Sale;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author gze
 * @ClassName: OrderRefundTask
 * @Description: (订单定时退款任务)
 * @date: 2020-05-29 16:01
 */
@Component("orderRefundTask")
@Slf4j
public class OrderRefundTask implements ITask{

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderStatusLogMapper orderStatusLogMapper;

    @Autowired
    private PayPalConfig payPalConfig;

    /*
     * 订单待退款订单退款
     * */
    @Transactional
    @Override
        // 0 */30 * * * ?
    public void run(String param) {
        log.info("订单定时退款任务开始！！！");
        //查询出所有已发货状态的订单
        List<Order> orderList = orderMapper.refundOrder();
        List<Order> orderUpList = new ArrayList<>();
        List<OrderStatusLog> logList = new ArrayList<>();
        APIContext apiContext = new APIContext(payPalConfig.getClientId(), payPalConfig.getClientSecret(), payPalConfig.getMode());
        if(orderList != null && !orderList.isEmpty()){
            for (Order order : orderList) {
                if(order.getPayPrice() == null || order.getPayPrice().compareTo(BigDecimal.ZERO) == 0){
                    continue;
                }
                //创建订单状态日志
                OrderStatusLog orderStatusLog = new OrderStatusLog();
                orderStatusLog.setUserId(order.getUserId());
                orderStatusLog.setOrderId(order.getOid());
                orderStatusLog.setOldStatus(order.getOrderStatus());
                orderStatusLog.setIsSys(IF.NO);
                Order orderUp = new Order();
                orderUp.setOid(order.getOid());
                orderUp.setUpdateTime(new Date());

                //创建退款请求
                Sale sale = new Sale();
                sale.setId(order.getPayPaymentsId());
                Amount amount = new Amount();
                amount.setCurrency(payPalConfig.getCurrency());
                RefundRequest refund = new RefundRequest();
                refund.setAmount(amount);
                amount.setTotal(order.getPayPrice().toString());
                refund.setReason("支付失败，退款");
                DetailedRefund res = null;
                try {
                    res = sale.refund(apiContext, refund);
                } catch (PayPalRESTException e) {
                    log.error("PayPalRESTException:",e);
                }

                orderStatusLog.setNewStatus(OrderStatusEnum.REFUNDED);
                orderStatusLog.setRemark(RemarkEnum.SHZT24);
                orderUp.setOrderStatus(OrderStatusEnum.REFUNDED);
                if(res == null || !res.getState().equals("completed")){
                    orderStatusLog.setNewStatus(OrderStatusEnum.REFUNDING);
                    orderStatusLog.setRemark(RemarkEnum.SHZT25);
                    orderUp.setOrderStatus(OrderStatusEnum.REFUNDING);
                }

                orderStatusLog.setCreateTime(new Date());
                orderStatusLog.setUpdateTime(new Date());
                logList.add(orderStatusLog);
                orderUp.setSignTime(new Date());
                orderUpList.add(orderUp);
            }
            //批量更新订单表
            if(!orderUpList.isEmpty()){
                orderUpList.stream().forEach(orderMapper::updateByKey);
            }

            //批量插入记录表
            if(!logList.isEmpty()){
                orderStatusLogMapper.insertBatchLog(logList);
            }
        }
        log.info("订单定时退款任务结束！！！");
    }
}
